 // 底部操作选择
 function loadJson(activeIndex) {

  (function(){
    var defaultOnTouchStartHandler = fabric.Canvas.prototype._onTouchStart;
    fabric.util.object.extend(fabric.Canvas.prototype, { 
      _onTouchStart: function(e) { 
        var target = this.findTarget(e);
        if (this.allowTouchScrolling && !target && !this.isDrawingMode) {
          this.canvas.discardActiveObject()
          this.canvas.renderAll()
          return;
        }
        defaultOnTouchStartHandler.call(this, e);
      } 
    });
  })();

  const jsonStr = '{"version":"5.2.1","objects":[{"type":"textbox","version":"5.2.1","originX":"left","originY":"top","left":215.82,"top":596.96,"width":200,"height":52.52,"fill":"#000","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"fontFamily":"Times New Roman","fontWeight":"normal","fontSize":14,"text":"落日溺在云层里，银河滑落一片掉进大海里，月光散落在森林里，该和你手牵手走在这浪漫里","underline":false,"overline":false,"linethrough":false,"textAlign":"left","fontStyle":"normal","lineHeight":1.16,"textBackgroundColor":"","charSpacing":0,"styles":{},"direction":"ltr","path":null,"pathStartOffset":0,"pathSide":"left","pathAlign":"baseline","minWidth":20,"splitByGrapheme":true},{"type":"image","version":"5.2.1","originX":"left","originY":"top","left":110.14,"top":272.44,"width":592,"height":128,"fill":"#fff","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.3,"scaleY":0.3,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://vs-m.szsszykj.com/handbook/7d28620220322105353727.png","crossOrigin":"anonymous","filters":[]},{"type":"path","version":"5.2.1","originX":"left","originY":"top","left":8.59,"top":11.88,"width":847.02,"height":784.49,"fill":"#AAB9E3","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.1,"scaleY":0.1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"path":[["M",512,122.176],["L",935.509333,388.928],["L",901.397333,443.072],["L",842.645333,406.058667],["L",842.666667,906.666667],["L",181.33333299999993,906.666667],["L",181.31199999999993,406.05866699999996],["L",122.60266699999993,443.07199999999995],["L",88.49066699999992,388.92799999999994],["L",512,122.176],["z"],["M",512,197.824],["L",245.312,365.76],["L",245.333333,842.666667],["L",778.6666670000001,842.666667],["L",778.645333,365.73866699999996],["L",512,197.824],["z"],["M",662.4,652.4159999999999],["L",662.4,716.4159999999999],["L",363.306667,716.4159999999999],["L",363.306667,652.4159999999999],["L",662.4,652.4159999999999],["z"],["M",662.4,481.749333],["L",662.4,545.749333],["L",363.306667,545.749333],["L",363.306667,481.749333],["L",662.4,481.749333],["z"]]}],"background":"#f8f8f8","backgroundImage":{"type":"image","version":"5.2.1","originX":"left","originY":"top","left":0,"top":0,"width":1242,"height":2208,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.33,"scaleY":0.29,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://st-gdx.dancf.com/gaodingx/0/uxms/design/20210909-185112-74cd.jpg","crossOrigin":"anonymous","filters":[]}}';
  const CanvasContentEl = document.querySelector(`#canvasContentEl`);
  // 现在画布的大小1.567745 1.416809605488851
  // const ratioNum = 1.418918918918919;
  const ratioNum = 1.683333333333333;
  let CW = window.innerWidth - 36;
  let CH = CW * ratioNum;

  if (CanvasContentEl.offsetHeight < CH) {
    CW -= 60;
    CH = CW * ratioNum;
  }
  this.canvas = new fabric.Canvas('canvas', {
    width: CW, // 画布宽度
    height: CH, // 画布高度
    backgroundColor: '#f8f8f8', // 画布背景色
    selection: false,
    allowTouchScrolling: false,
    enableRetinaScaling: true,
  })

  // 计算现在画布大小的比例
  const ratioX = CW / 414;
  const ratioY = CH / 649.04643;

  const loadJsonParams = JSON.parse(jsonStr);
  console.log(loadJsonParams);

  // 计算背景的大小
  loadJsonParams.backgroundImage.scaleX *= ratioX;
  loadJsonParams.backgroundImage.scaleY *= ratioY;

  if (loadJsonParams && loadJsonParams.objects && loadJsonParams.objects.length > 0) {
    loadJsonParams.objects.forEach(element => {
      // element.shadow = '1px 1px';
      // element.charSpacing = 100;
      element.scaleX *= ratioX;
      element.scaleY *= ratioY;
      element.left *= ratioX;
      element.top *= ratioY;
    });
  }

  this.canvas.loadFromJSON(loadJsonParams, this.canvas.renderAll.bind(this.canvas));
  const CanvasContainer = document.querySelector('.canvas-container');
  if (CanvasContentEl.offsetHeight > CanvasContainer.offsetHeight) {
    // CanvasContainer.style.position = 'absolute';
  } else {
    this.canvas.allowTouchScrolling = true;
    this.canvas.renderAll();
  }
}

// 初始化fabric
function initFabric() {
  (function(){
    var defaultOnTouchStartHandler = fabric.Canvas.prototype._onTouchStart;
    fabric.util.object.extend(fabric.Canvas.prototype, { 
      _onTouchStart: function(e) { 
        var target = this.findTarget(e);
        if (this.allowTouchScrolling && !target && !this.isDrawingMode) {
          canvas.discardActiveObject()
          canvas.renderAll()
          return; 
        }
        defaultOnTouchStartHandler.call(this, e); 
      } 
    });
  })();

  // const CanvasContentEl = document.querySelector('#canvasContentEl');
  canvas = new fabric.Canvas('canvas', {
    width: window.innerWidth, // 画布宽度
    height: window.innerWidth * 1.567745, // 画布高度
    backgroundColor: '#f8f8f8', // 画布背景色
    selection: false,
    allowTouchScrolling: true,
    enableRetinaScaling: true,
  })

  // 更换背景图片
  fabric.Image.fromURL('https://st-gdx.dancf.com/gaodingx/0/uxms/design/20210909-185112-74cd.jpg', function(img) {
    console.log(canvas.height);
    canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
      scaleX: canvas.width / img.width,
      scaleY: canvas.height / img.height
    });
  }, {crossOrigin: 'anonymous'});

  new fabric.Image.fromURL('https://vs-m.szsszykj.com/handbook/7d28620220322105353727.png', (img) => {
      img['setControlVisible']('ml',false)
      img['setControlVisible']('mb',false)
      img['setControlVisible']('mr',false)
      img['setControlVisible']('mt',false)
      img.set({left: 3, top: 50, selection: false, scaleX: 0.3, scaleY: 0.3, fill: '#fff', opacity: 1});
      canvas.add(img);
  }, {crossOrigin: 'anonymous'});

  fabric.loadSVGFromURL('https://phone-res.jiaxianghui.cn/icon.svg', function(objects, options) {
      var drink = fabric.util.groupSVGElements(objects, options);
      drink.fill = "#AAB9E3"
      console.log(drink)
      canvas.add(drink); 
      canvas.calcOffset();
      canvas.renderAll();
  }); 


  // 圆形
  const text = new fabric.Textbox('落日溺在云层里，银河滑落一片掉进大海里，月光散落在森林里，该和你手牵手走在这浪漫里', {
      left: 25, 
      top: canvas.height / 2,
      width: 200,
      fill: '#000',
      fontSize: 14,
      splitByGrapheme: true,
      editable: false,
      transparentCorners: false,
      cornerColor: 'blue',
      cornerStrokeColor: 'red',
      borderColor: 'red',
      cornerSize: 12,
      padding: 10,
      cornerStyle: 'circle',
      borderDashArray: [3, 3],
  })

  text['setControlVisible']('mb',false)
  // circle['setControlVisible']('mr',false)
  text['setControlVisible']('mt',false)
  canvas.add(text) // 将圆形添加到 canvas 画布里
}

function handleToJson() {
  console.log(JSON.stringify(canvas.toJSON()));
}

function handleSaveImage() {
  const ext = "png";
  const base64 = canvas.toDataURL({
      format: ext,
      enableRetinaScaling: true
  });
  console.log(base64);
  const link = document.createElement("a");
  link.href = base64;
  link.download = `eraser_example.${ext}`;
  link.click();
}